package com.vista.questionnaire.web.rest.util;


import com.vista.questionnaire.domain.Question;
import com.vista.questionnaire.domain.enumeration.QuestionEnum;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import static com.vista.questionnaire.domain.ParamsContents.*;


@Component
public class PraseTagUtils {

    private Question praseTag(Stream<Element> elementStream, int indexInExamination) {
        StringBuilder stringBuilder = new StringBuilder();
        Question question = new Question();
        elementStream.forEach(element1 -> {//一个题目一个id，绝对不可以重复
                stringBuilder.append(element1.toString());
                if (StringUtils.isEmpty(question.getName()) && StringUtils.isEmpty(question.getY())) {
                    Attributes attributes = element1.attributes();
                    question.setName(attributes.get(NAME));
                    question.setY(attributes.get(Y));
                    question.setDocumentID(attributes.get(ID));
                    question.setType(QuestionEnum.getEnum(attributes.get(Type)));
                    question.setIndexInExamination(indexInExamination);
                }
            }
        );

        question.setContent(stringBuilder.toString());
        return question;
    }

    public List<Question> praseTags(String content) {
//        content.replace('\'', '\"');
        List<Question> rtn = new ArrayList<>();
        Document document = Jsoup.parse(content);
        List<Element> inputElements = document.getElementsByTag(INPUT);//找出所有特殊定义的tag元素（其实就是题目）
        ArrayList<String> nameSet = new ArrayList<>();
        inputElements.forEach(element ->
        {
            if (!nameSet.contains(element.attributes().get(NAME)))
                nameSet.add(element.attributes().get(NAME));
        });
        nameSet.remove("");
        //使用了并行流之后数据乱序，这里加上一个试卷内序号
//        nameSet.parallelStream().forEach(s -> {
////            int index = nameSet.indexOf(s);
////            rtn.add(praseTag(inputElements.stream().filter(element -> element.attributes().get(NAME).equals(s)), index));
////        });
        nameSet.forEach(s -> {
            int index = nameSet.indexOf(s);
            rtn.add(praseTag(inputElements.stream().filter(element -> element.attributes().get(NAME).equals(s)), index));
        });
        return rtn;
    }

}
